import { LaptopOutlined, UserOutlined } from '@ant-design/icons';
import { Dropdown, Layout, Menu, MenuProps } from 'antd';
import { Footer } from 'antd/es/layout/layout';
import { dateUtils } from 'my-ts-core';
import { AuthenticationService } from 'my-web-core/auth';
import React, { useEffect, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';

import AuthService from '@/features/authentication/services/auth-service';
import UserAvatar from '@/features/users/components/UserAvatar';
import AuthenticationSlice from '@/shared/redux/authentication-slice';
import Hook from '@/shared/redux/hook';

import '@/MainView.css';

function MainView() {
  const { Header, Content, Sider } = Layout;
  const location = useLocation();
  const currentUser = Hook.useAppSelector((state) => state.authentication.currentUser);
  const dispatch = Hook.useAppDispatch();
  const navigate = useNavigate();

  // We need to select the menu item when:
  // - User saves authentication status and opens a url directly. Such like /users/list.
  // - User is redirected to /users/list from login.
  const [defaultSelectedKeys, setDefaultSelectedKeys] = useState<string[]>(
    location.pathname.endsWith('login') ? ['/home'] : [location.pathname],
  );

  // Top-Right pop menu.
  const items = [
    {
      label: '修改资料',
      key: '0',
    },
    {
      label: <div onClick={logout}>退出登录</div>,
      key: '1',
    },
  ];

  type MenuItem = Required<MenuProps>['items'][number];

  const sideMenuItems: MenuProps['items'] = [
    getItem('首页', '/home', <LaptopOutlined />),
    getItem('用户', '/user', <UserOutlined />, [getItem('列表', '/users/list')]),
  ];

  useEffect(() => {
    if (!location.pathname.endsWith('login')) {
      setDefaultSelectedKeys([location.pathname]);
    }
  }, [location.pathname]);

  function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
    type?: 'group',
  ): MenuItem {
    return {
      key,
      icon,
      children,
      label,
      type,
    } as MenuItem;
  }

  function sideMenuClick(e: any) {
    navigate(e.key);
  }

  function logout(): void {
    new AuthService().logout();
    navigate('/authentication/login', { replace: true });
    dispatch(AuthenticationSlice.changeIsAuthenticated(AuthenticationService.isAuthenticated));
    dispatch(AuthenticationSlice.changeCurrentUser(AuthenticationService.currentUser));
  }

  return (
    <Layout className="MainView-root-container">
      {currentUser && (
        <Header className="header MainView-header">
          <img src="./assets/images/logo.png" className="MainView-logo" alt="logo" />
          <h3 className="MainView-header-title">平台管理系统</h3>
          <div className="MainView-header-user">
            <Dropdown menu={{ items }}>
              <div onClick={(e) => e.preventDefault()}>
                <UserAvatar {...currentUser} />
              </div>
            </Dropdown>
          </div>
        </Header>
      )}
      <Layout>
        {currentUser && (
          <Sider width={200}>
            <Menu
              mode="inline"
              defaultSelectedKeys={defaultSelectedKeys}
              defaultOpenKeys={['/user']}
              style={{ height: '100%', borderRight: 0 }}
              items={sideMenuItems}
              onClick={sideMenuClick}
            />
          </Sider>
        )}
        <Layout style={currentUser ? { padding: '0px 0px 24px 10px' } : {}}>
          {/* <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>Home</Breadcrumb.Item>
            <Breadcrumb.Item>List</Breadcrumb.Item>
            <Breadcrumb.Item>App</Breadcrumb.Item>
          </Breadcrumb> */}
          <Content
            className="MainView-site-layout-background"
            style={
              currentUser
                ? {
                    padding: 24,
                    margin: 0,
                    minHeight: 280,
                  }
                : {}
            }
          >
            <Outlet />
          </Content>
          {currentUser && (
            <Footer className="MainView-footer">
              Ant Design ©{dateUtils.getCurrentDate().getFullYear()} Created by Ant UED
            </Footer>
          )}
        </Layout>
      </Layout>
    </Layout>
  );
}

export default MainView;
